package com.example.springbootbook2.controller;

import com.example.springbootbook2.model.BookInfo;
import com.example.springbootbook2.model.PageRequest;
import com.example.springbootbook2.model.PageResult;
import com.example.springbootbook2.service.BookInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/book")
public class BookInfoController {
    @Autowired
    private BookInfoService bookInfoService;

    @RequestMapping("/getBookInfoByPage")
    public PageResult getBookInfoByPage(PageRequest pageRequest) {
        if (pageRequest==null || pageRequest.getCurrentPage()<=0 || pageRequest.getOffset()<0) {
            return null;
        }
        log.info("根据page查询书籍:pageRequest{}",pageRequest);
        return bookInfoService.getBookInfoByPage(pageRequest);
    }

    @RequestMapping("/addBook")
    public String addBook(BookInfo bookInfo, HttpServletRequest request) {
        log.info("增加图书:bookinfo{}",bookInfo);
        if (bookInfo==null || !StringUtils.hasLength(bookInfo.getBookName())
        || !StringUtils.hasLength(bookInfo.getAuthor())
        || !StringUtils.hasLength(bookInfo.getPublish())
        || bookInfo.getCount() <= 0
        || bookInfo.getPrice() == null) {
            return "图书信息出现错误，请检查参数后重新添加";
        }
        return bookInfoService.addBook(bookInfo);
    }

    @RequestMapping("/queryBookInfoById")
    public BookInfo queryBookInfoById(Integer id) {
        log.info("根据ID查询书籍:id{}",id);
        if (id == null || id <= 0) return null;
        return bookInfoService.queryBookInfoById(id);
    }

    @RequestMapping("/updateBook")
    public String updateBook(BookInfo bookInfo) {
        log.info("updateBook修改图书:bookInfo{}",bookInfo);
        if (bookInfo == null) return "";
        return bookInfoService.updateBook(bookInfo);
    }

    @RequestMapping("/deleteBook")
    public String deleteBook(Integer id) {
        return bookInfoService.deleteBook(id);
    }

    public String batchDelete(@RequestParam List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return "参数传递错误，请检查后再操作";
        }
        return bookInfoService.batchDelete(ids);
    }
}
